package com.mzy.tomcat;

import com.mzy.tomcat.handler.MzyRequestHandler;
import com.mzy.tomcat.servlet.MzyHttpServlet;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * V2 版本 基于xml文件实现servlet
 */
public class MzyTomcatV2 {

    public static final ConcurrentHashMap<String, String> servletUrlMapping = new ConcurrentHashMap<>();
    public static final ConcurrentHashMap<String, MzyHttpServlet> servletClassMapping = new ConcurrentHashMap<>();


    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(8080);
        init();
        System.out.println("============8080端口监听中============");
        while (!serverSocket.isClosed()) {
            Socket socket = serverSocket.accept();
            new Thread(new MzyRequestHandler(socket)).start();
        }
        serverSocket.close();
    }

    public static void init() throws DocumentException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        InputStream is = MzyTomcatV2.class.getResourceAsStream("/web.xml");
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(is);
        Element rootElement = document.getRootElement();
        List<Element> elements = rootElement.elements();
        for (Element element : elements) {
            if ("servlet".equalsIgnoreCase(element.getName())) {
                Element servletName = element.element("servlet-name");
                Element servletClass = element.element("servlet-class");
                Class<?> clazz = Class.forName(servletClass.getText());
                MzyHttpServlet instance = ((MzyHttpServlet) clazz.newInstance());
                servletClassMapping.put(servletName.getText().trim(), instance);
            } else if ("servlet-mapping".equalsIgnoreCase(element.getName())) {
                Element servletName = element.element("servlet-name");
                Element urlPattern = element.element("url-pattern");
                servletUrlMapping.put(urlPattern.getText().trim(), servletName.getText().trim());
            }
        }

    }


}
